package cn.iocoder.yudao.module.mqtt.util;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpSysUtil {
	private final static Logger logger = LoggerFactory.getLogger(HttpSysUtil.class);


	/**
	 * 请求市联网中心
	 * @param url 市联网中心URl
	 * @param params json参数
	 * @return 
	 */
	public static String doPost(String url, String params, String token) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Content-Type", "application/json");
		//httpPost.setHeader("AuthCode",GaosuUtil.getGsProperties().getHttpAuthCode());
		if(ObjUtil.isNotEmpty( token)){
			httpPost.setHeader("Authorization=", token);
		}


		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			String jsonString = EntityUtils.toString(responseEntity,"utf-8");
			return jsonString;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	public static Map<String,Object> postToken(String url, String params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setHeader("Authorization", "Basic eGNsb3VkLWFkbWluOjEyMzQ1Ng==");

		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			String jsonString = EntityUtils.toString(responseEntity,"utf-8");
//			System.out.println(jsonString);
			if(200 == response.getStatusLine().getStatusCode() && ObjUtil.isNotEmpty(jsonString)) {
				Map<String,Object> responseResult = JSONUtil.toBean(jsonString, Map.class);
				return responseResult;
			}else {
				logger.info("发送失败返回="+response.getStatusLine().getStatusCode()+"，内容="+jsonString);
				//throw new ServiceException(response.getStatusLine().getStatusCode(), jsonString);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			//throw new ServiceException(502, "ClientProtocolException异常");
		} catch (IOException e) {
			e.printStackTrace();
		//	throw new ServiceException(503, "IOException异常");
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}



	/**
	 * 带参数和请求头的GET请求
	 *
	 * @param url    请求地址
	 * @param param  请求参数
	 * @param header 请求头
	 * @return java.lang.String
	 * @date 2018-9-25 20:09
	 */
	public static String doGet(String url, Map<String, String> param, Map<String, String> header) {
		String resultString = "";
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpGet httpGet = buildHttpGet(url, param);
			if (header != null) {
				for (String key : header.keySet()) {
					httpGet.setHeader(key, header.get(key));
				}
			}
			try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
				if (response.getStatusLine().getStatusCode() == 200) {
					resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultString;
	}



	private static HttpGet buildHttpGet(String url, Map<String, String> param) throws URISyntaxException {
		URIBuilder builder = new URIBuilder(url);
		if (param != null) {
			for (String key : param.keySet()) {
				builder.addParameter(key, param.get(key));
			}
		}
		URI uri = builder.build();
		return new HttpGet(uri);
	}

}
